package next.fire.spinus.logx.utils.codec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Created by daibing on 2023/4/21.
 */
public class GZip {

    /**
     * 字节流gzip压缩
     */
    public static byte[] doZip(byte[] input) {
        if (input == null || input.length == 0) {
            return null;
        }
        byte[] b = null;
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(input);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream zip = new GZIPOutputStream(out);
            byte[] buffer = new byte[4096];
            int n = 0;
            while ((n = in.read(buffer, 0, buffer.length)) > 0) {
                zip.write(buffer, 0, n);
            }
            zip.flush();
            zip.close();
            in.close();
            b = out.toByteArray();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return b;
    }

    public static byte[] doZip(String input) {
        return doZip(input.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * gzip解压
     */
    public static byte[] doUnzip(byte[] input) {
        if (input == null || input.length == 0) {
            return null;
        }
        // 创建一个新的输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(input);
            GZIPInputStream zip = new GZIPInputStream(in);
            byte[] buffer = new byte[4096];
            int n = 0;
            // 将解压后的数据写入输出流
            while ((n = zip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            in.close();
            zip.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    public static byte[] doUnzip(String input) {
        return doUnzip(input.getBytes(StandardCharsets.UTF_8));
    }
}
